import React, { Component, Fragment } from 'react';
import { AnyAction, Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Modal,
  Table,
  Button,
  message,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

import SaveExpress from './components/SaveExpress';

const { pathname } = window.location;

interface CouierListProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: any;
  detailInfo: any;
  location: { query: any };
  lookupList: AnyAction;
  screen: string;
}

interface CouierListState {
  tariffId: number;
  name: string;
  pageIndex: number;
  pageSize: number;
  saveVisible: boolean;
  deleteId: number;
  deleteVisible: boolean;
  rowId:number;
}

@connect(({
  SendAPackageCourier: { dataInfo, lookupList },
  common: { INITINFO },
  global: { screen },
}: any) => ({
  dataInfo, INITINFO, lookupList, screen,
}))

class CouierListElem extends Component<CouierListProps, CouierListState> {
  columns = [
    { title: 'ID', dataIndex: 'id', width: '20%' },
    { title: '快递公司', dataIndex: 'name', width: '20%' },
    { title: '固定电话', dataIndex: 'telephone', width: '20%' },
    { title: '创建时间', dataIndex: 'createTime', width: '25%' },
    {
      title: '操作',
      width: '15%',
      render: (text: any, record: any) => (
        <div
          className="operLink"
          onClick={this.handleDelete.bind(this, record)}
        >删除
        </div>
      ),
    },
  ];

  state: CouierListState = {
    tariffId: 0,
    name: '',
    pageIndex: 1,
    pageSize: 20,
    saveVisible: false,
    deleteId: 0,
    deleteVisible: false,
    rowId: 0,
  }

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const {
      location: {
        query: {
          pageIndex,
          pageSize,
          tariffId,
          name,
        },
      },
    } = nextProps;

    if (!tariffId) {
      message.warning('当前配置不存在');
      return null;
    }
    return {
      tariffId,
      name,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.fetchAction('common/fetchAreaList');
    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { tariffId, pageIndex, pageSize } = this.state;
    if (tariffId !== prevState.tariffId
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize) {
      this.fetchDataValues();
    }
  }

  fetchDataValues = () => {
    const params = this.getQueryParams();
    this.fetchAction('fetch', params);
  }

  getQueryParams = () => {
    const { tariffId, pageIndex, pageSize } = this.state;
    const params = {
      tariffId,
      pageIndex,
      pageSize,
    };
    return params;
  }

  handleDelete = ({ id }: any) => {
    this.setState({
      deleteId: id,
      deleteVisible: true,
    });
  }

  handleConfirm = () => {
    const { deleteId: expressId, pageIndex, pageSize } = this.state;
    const { location: { query: { tariffId } } } = this.props;

    const params = {
      searchValues: { pageIndex, pageSize, tariffId },
      payload: { tariffId, expressId },
    };
    this.fetchAction('deleteExpress', params);
    this.handleCancel();
  }

  handleCancel = () => {
    this.setState({
      deleteId: 0,
      deleteVisible: false,
    });
  }

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { tariffId, name } = this.state;
    const query = {
      tariffId,
      pageIndex,
      pageSize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `配置${name}`,
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  }

  handleSave = (value: boolean) => {
    this.setState({ saveVisible: value });

    const { location: { query: { id: tariffId } } } = this.props;
    const params = {
      pageIndex: 1,
      pageSize: 20,
      tariffId,
    };
    this.fetchAction('fetchAllExpressList', params);
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `SendAPackageCourier/${typeName}`;
    const { dispatch } = this.props;
    dispatch({ type, payload });
  }

  render() {
    const {
      pageIndex,
      pageSize,
      saveVisible,
      deleteVisible,
    } = this.state;

    const {
      dataInfo,
      lookupList,
      location: { query },
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: any = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="tableList marginT12">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleSave.bind(this, true)}
            >新增
            </Button>
          </div>

          <Table
            rowKey="id"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />

          <Modal
            title="操作提示"
            visible={deleteVisible}
            onOk={this.handleConfirm}
            onCancel={this.handleCancel}
          >
            <p style={{ textAlign: 'center' }}>确定要删除当前快递公司吗？</p>
          </Modal>

          <SaveExpress
            saveVisible={saveVisible}
            lookupList={lookupList}
            id={query.tariffId}
            handleCancel={this.handleSave.bind(this)}
            fetchAction={this.fetchAction.bind(this)}
          />
        </Card>
      </Fragment>
    );
  }
}
export default Form.create<CouierListProps>()(CouierListElem);
